package com.ruben.activity;

import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.imagepreview.R;
import com.ruben.adapter.MainImageListAdapter;
import com.ruben.interfaces.ListDataListener;
import com.ruben.pojo.ImagePreview;
import com.ruben.utils.ToastUtils;
import com.ruben.widgets.LinearRecyclerView;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.stream.Collectors;

import lombok.SneakyThrows;
import okhttp3.RequestBody;

public class MainImageListActivity extends AppCompatActivity implements View.OnClickListener, ListDataListener {

    public static boolean flag = true;
    public static String WEB_URL = "http://lab.mkblog.cn/wallpaper/api.php";
    public static boolean antiShakeFlag = false;
    private MainImageListAdapter adapter;
    private List<ImagePreview> dataList = new ArrayList<>(10);
    private SwipeRefreshLayout refreshLayout;
    private LinearRecyclerView imageListView;
    private Map<String, RequestBody> paraMap = new HashMap<>();
    private int pageNum = 0;
    private int pageSize = 30;

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_image_list);
        initView();
        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    private void initView() {
        imageListView = findViewById(R.id.main_image_list_recycle_view_image_list);
        refreshLayout = findViewById(R.id.main_image_list_swipe_refresh_layout_image_list);
        imageListView.setRefreshLayout(refreshLayout);
        imageListView.setListDataListener(this);
        imageListView.setLinearLayoutManager();
        imageListView.setHasFixedSize(true);
        adapter = new MainImageListAdapter(this, dataList);
        imageListView.setAdapter(adapter);
    }

    @Override
    public void onClick(View v) {

    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void loadMore() {
        if (antiShakeFlag) {
            ToastUtils.shortToast("您划得太快了，稍等一下哦");
            imageListView.refreshFinish();
            return;
        }
        antiShakeFlag = true;
        pageNum += 30;
        getImageData();
        new Timer().schedule(new TimerTask() {
            public void run() {
                antiShakeFlag = false;
            }
        }, 10000);
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void refresh() {
        pageNum = 0;
        loadMore();
    }

    /**
     * @MethodName: getImageData
     * @Description: 我还没有写描述
     * @Date: 2020/10/17 0017 2:50
     * *
     * @author: <achao1441470436@gmail.com>
     * @param: []
     * @returnValue: void
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    @SneakyThrows
    private void getImageData() {
        imageListView.loading();
        List<String> imageList = goToJail("26", String.valueOf(pageNum), String.valueOf(pageSize));
        imageListView.refreshFinish();
        if (flag) {
            imageList = imageList.stream().sorted(Comparator.comparing(String::hashCode)).collect(Collectors.toList());
            flag = false;
        } else {
            flag = true;
        }
        dataList.addAll(imageList.stream().map(data -> {
            ImagePreview imagePreview = new ImagePreview();
            imagePreview.setUrl(data);
            return imagePreview;
        }).collect(Collectors.toList()));
        adapter.notifyDataSetChanged();
    }

    public List<String> goToJail(String type, String pageNum, String pageSize) throws IOException {
        Connection connection = Jsoup
                // 设置URL
                .connect(WEB_URL + "?cid=" + type + "&start=" + pageNum + "&count=" + pageSize + "")
                // 忽略解析不了的类型，强制解析，避免UnsupportedMimeTypeException
                .ignoreContentType(true)
                // 设置超时时间(ms)
                .timeout(60000);
        // 发送get请求，获取返回结果
        Document document = connection.get();
        // 获取body里的内容
        String jsonString = document.getElementsByTag("body").text();
        // 解析json
        JSONArray elements = JSON.parseObject(jsonString).getJSONArray("data");
        List<String> images = new ArrayList<>(10);
        for (int i = 0; i < Integer.parseInt(pageSize); i++) {
            JSONObject jsonObject = JSON.parseObject(elements.get(i).toString());
            // 获取到我们需要的图片url
            String image = jsonObject.getString("img_1600_900");
            // 添加到list里
            images.add(image);
        }
        //返回
        return images;
    }
}